package com.frejoys.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frejoys.common.dto.admin.AgentRoleGroupIdDto;
import com.frejoys.common.dto.agent.AgentUserSaveDto;
import com.frejoys.common.dto.agent.AgentUserUpdateDto;
import com.frejoys.common.dto.common.IdDto;
import com.frejoys.common.enums.EStatus;
import com.frejoys.common.enums.EUserRole;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.util.CommonUtil;
import com.frejoys.common.util.TimeUtil;
import com.frejoys.common.vo.agent.AgentUserVo;
import com.frejoys.dao.entity.AgentRoleGroup;
import com.frejoys.dao.entity.AgentUser;
import com.frejoys.dao.entity.User;
import com.frejoys.dao.mapper.AgentRoleGroupMapper;
import com.frejoys.dao.mapper.AgentUserMapper;
import com.frejoys.dao.mapper.UserMapper;
import com.frejoys.service.AgentUserService;
import com.frejoys.service.UserService;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class AgentUserServiceImpl extends ServiceImpl<AgentUserMapper, AgentUser> implements AgentUserService {

    private final UserService userService;

    private final UserMapper userMapper;

    private final AgentRoleGroupMapper agentRoleGroupMapper;

    @Override
    public Integer getAgentRoleGroupId(Long userId) {
        LambdaQueryWrapper<AgentUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(AgentUser::getAgentRoleGroupId).eq(AgentUser::getUserId, userId);
        AgentUser e = getOnly(wrapper);
        return e != null ? e.getAgentRoleGroupId() : null;
    }

    /**
     * 设置代理用户到代理用户组
     *
     * @param dto
     */
    @Override
    public boolean saveAgentUser(AgentUserSaveDto dto) {
        List<User> users = userService.getSimpleListUser(dto.getUserIds());

        //校验
        if (users.isEmpty()){
            throw new GeneralException(HttpStatus.agentError);
        }
        users.forEach(user -> {
            validatedUser(user, null);
        });

        List<AgentUser> list = new ArrayList<>();

        for (User user:users) {
            AgentUser agentUser = new AgentUser();
            agentUser.setUserId(user.getId());
            agentUser.setAgentRoleGroupId(dto.getAgentRoleGroupId());
            agentUser.setCreateTime(TimeUtil.unixTime());
            list.add(agentUser);
        }

        if (!list.isEmpty()){
            saveBatch(list);
        }
        return true;
    }

    /**
     * 修改代理用户到代理用户组
     *
     * @param dto
     */
    @Override
    public boolean updateAgentUser(AgentUserUpdateDto dto) {
        User user = userService.getSimpleUser(dto.getUserId());
        validatedUser(user, dto.getId());
        LambdaUpdateWrapper<AgentUser> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(AgentUser::getUserId, dto.getUserId());

        if (dto.getAgentRoleGroupId() != null) {
            wrapper.set(AgentUser::getAgentRoleGroupId, dto.getAgentRoleGroupId());
        }
        return update(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSaveAgentUser(IdDto dto) {
        baseMapper.deleteById(dto.getId());
        return true;
    }

    @Override
    public IPage<AgentUserVo> agentListInfo(AgentRoleGroupIdDto dto) {
        Page page = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<AgentUser> wrapper = new LambdaQueryWrapper<>();

        if (dto.getId() != null){
            wrapper.eq(AgentUser::getAgentRoleGroupId,dto.getId());
        }
        if (StrUtil.isNotEmpty(dto.getPhone())){
            Long userId = userMapper.phoneByUserId(dto.getPhone());

            if (userId == null){
                return new Page<>();
            }
            wrapper.eq(AgentUser::getUserId,userId);
        }
        if (StrUtil.isNotEmpty(dto.getName())){
            List<Integer> agentRoleGroupIds = agentRoleGroupMapper.getNameById(dto.getName());

            if (agentRoleGroupIds.isEmpty()){
                return new Page<>();
            }
            wrapper.in(AgentUser::getAgentRoleGroupId,agentRoleGroupIds);
        }
        wrapper.orderByDesc(AgentUser::getCreateTime);
        Page<AgentUser> agentUserPage = baseMapper.selectPage(page, wrapper);
        IPage<AgentUserVo> agentUserVos = agentUserPage.convert(agentUser -> BeanUtil.copyProperties(agentUser, AgentUserVo.class));
        List<AgentUserVo> list = agentUserVos.getRecords();

        if (!list.isEmpty()){
            List<Long> userIds = list.stream().map(AgentUserVo::getUserId).toList();

            //查询代理组名字
            List<Integer> agentRoleGroupIds = list.stream().map(AgentUserVo::getAgentRoleGroupId).toList();
            LambdaQueryWrapper<AgentRoleGroup> agentUserWrapper = new LambdaQueryWrapper<>();
            agentUserWrapper.select(AgentRoleGroup::getId,AgentRoleGroup::getName)
                    .in(AgentRoleGroup::getId,agentRoleGroupIds);
            List<AgentRoleGroup> agentRoleGroups = agentRoleGroupMapper.selectList(agentUserWrapper);
            Map<Integer, String> agentRoleGroupNameMap = agentRoleGroups.stream().collect(Collectors.toMap(AgentRoleGroup::getId, AgentRoleGroup::getName));

            //查询用户信息
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(User::getId,userIds);
            List<User> users = userMapper.selectList(queryWrapper);
            Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId, user -> user));
            for (AgentUserVo vo:list) {
                if (userMap.containsKey(vo.getUserId())){
                    User user = userMap.get(vo.getUserId());
                    vo.setUserId(user.getId());
                    vo.setPhone(user.getPhone());
                    vo.setNickname(user.getNickname());
                    vo.setAgentRoleGroupName(agentRoleGroupNameMap.get(vo.getAgentRoleGroupId()));
                }
            }
        }
        return agentUserVos;
    }

    /**
     * 验证用户
     *
     * @param user
     */
    private void validatedUser(User user, Integer id) {
        if (ObjectUtils.isEmpty(user)) {
            throw new GeneralException(HttpStatus.agentRoleNoExist);
        }

        if (user.getStatus().equals(EStatus.del.getValue())) {
            //用户被禁止登录
            throw new GeneralException(HttpStatus.extendUserLoginError);
        }

        //用户角色只能是代理
        if (!CommonUtil.bitExistOffset(user.getRole(), EUserRole.agent.getValue())) {
            throw new GeneralException(HttpStatus.agentError);
        }

        //验证该角色是否属于组
        LambdaQueryWrapper<AgentUser> wrapper = Wrappers.lambdaQuery();
        wrapper.select(AgentUser::getId).eq(AgentUser::getUserId, user.getId());
        if (id != null) {
            wrapper.ne(AgentUser::getId, id);
        }
        AgentUser agentUser = getOnly(wrapper);
        if (ObjectUtil.isNotEmpty(agentUser)) {
            throw new GeneralException(HttpStatus.agentUserHasGroup);
        }
    }
}
